﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DatabaseComponent;
using System.IO;

public partial class SupportVideoEditEN : System.Web.UI.Page
{

    

    string strChangedFiles = "";


    public List<SupportVideos> lstSupportVideosGrid
    {
        get
        {
            if (ViewState["lstSupportVideosGrid"] == null)
            {
                ViewState["lstSupportVideosGrid"] = System.Guid.NewGuid().ToString();
            }


            if (Session[ViewState["lstSupportVideosGrid"].ToString()] == null)
            {
                Session[ViewState["lstSupportVideosGrid"].ToString()] = new List<SupportVideos>();

            }

            return (List<SupportVideos>)Session[ViewState["lstSupportVideosGrid"].ToString()];

        }
        set
        {
            if (ViewState["lstSupportVideosGrid"] == null)
            {
                ViewState["lstSupportVideosGrid"] = System.Guid.NewGuid().ToString();
            }

            Session[ViewState["lstSupportVideosGrid"].ToString()] = value;
        }   
   
   

    }




    long mSupportVideosID
    {
        get
        {
            if (ViewState["mSupportVideosID"] == null)
            {
                ViewState["mSupportVideosID"] = System.Guid.NewGuid().ToString();
            }


            if (Session[ViewState["mSupportVideosID"].ToString()] == null)
            {
                long obj = -1;
                Session[ViewState["mSupportVideosID"].ToString()] = obj;

            }

            return (long)Session[ViewState["mSupportVideosID"].ToString()];

        }
        set
        {
            if (ViewState["mSupportVideosID"] == null)
            {
                ViewState["mSupportVideosID"] = System.Guid.NewGuid().ToString();
            }

            Session[ViewState["mSupportVideosID"].ToString()] = value;
        }
    }


    SupportVideos mObjSupportVideos
    {
        get
        {
            if (ViewState["mObjSupportVideos"] == null)
            {
                ViewState["mObjSupportVideos"] = System.Guid.NewGuid().ToString();
            }


            if (Session[ViewState["mObjSupportVideos"].ToString()] == null)
            {
                Session[ViewState["mObjSupportVideos"].ToString()] = new SupportVideos();

            }

            return (SupportVideos)Session[ViewState["mObjSupportVideos"].ToString()];

        }
        set
        {
            if (ViewState["mObjSupportVideos"] == null)
            {
                ViewState["mObjSupportVideos"] = System.Guid.NewGuid().ToString();
            }

            Session[ViewState["mObjSupportVideos"].ToString()] = value;
        }
    }



    Persons mobjUser
    {
        get
        {
            if (ViewState["mobjUser"] == null)
                ViewState["mobjUser"] = System.Guid.NewGuid().ToString();

            return Session[ViewState["mobjUser"].ToString()] as Persons;
        }
        set
        {
            if (ViewState["mobjUser"] == null)
                ViewState["mobjUser"] = System.Guid.NewGuid().ToString();

            Session[ViewState["mobjUser"].ToString()] =  value;
        }
    }






    protected void Page_Load(object sender, EventArgs e)
    {



       
       
        if (!Page.IsPostBack)
        {
            mobjUser = GlobalVars.getCurrentPerson();
            checkSecurityAndCustomizePage(mobjUser);
            bindGrid("");
            editLoad();
        }

        

    }



    /// <summary>
    /// this function will bind the grid 
    /// </summary>
    protected void bindGrid(string strIn)
    {

        List<SupportVideos> lstSupportVideos = search(strIn);



        lstSupportVideosGrid = lstSupportVideos;

        grdUsers.DataSource = lstSupportVideos;
        grdUsers.DataBind();
    }



    /// <summary>
    /// it will check the security and customize the page
    /// </summary>
    /// <param name="currentPerson">the person to set security to his previleges</param>
    protected void checkSecurityAndCustomizePage(Persons currentPerson)
    {
        //Security Check

        if (!currentPerson.lstAllRulesIDs.Contains((long)RulesEnum.Show_Support_Videos))
            Response.Redirect("LoginEN.aspx");


        if (!currentPerson.lstAllRulesIDs.Contains((long)RulesEnum.Edit_Support_videos))
        {
            btnSave.Enabled = false;
            btnDelete.Enabled = false;
        }
       




    }
    
    protected void btnSearch_Click(object sender, EventArgs e)
    {

        bindGrid(txtSearch.Text);
       
    }

    /// <summary>
    /// this function will search in hints and return the values
    /// </summary>
    /// <param name="txtText">the text to search for</param>
    /// <returns>a list of hints matched</returns>
    protected List<SupportVideos> search(string txtText)
    {
        SupportVideosDB objSupportVideosDB = new SupportVideosDB(ConnectionStrings.LMS);
        List<SupportVideos> lstRet = new List<SupportVideos>();
        if (txtText.Trim() == "")
        {
            List<SupportVideos> lstNew = objSupportVideosDB.Select(" top 100 ", " order by [VideoTitleEN] ");
            //lstNew = new List<TicketType>(from objFol in lstNew where objFol.StatusID != 2 select objFol);
            //no status
            return lstNew;
        }

        string[] strValues = null;
        if (txtText.Trim()[0] == '\"' && txtText.Trim()[txtText.Trim().Length - 1] == '\"')
        {
            try
            {
                strValues = new string[] { txtText.Trim().Substring(1, txtText.Trim().Length - 2) };
                if (strValues[0] == "")
                    strValues = new string[0];
            }
            catch
            {
                strValues = new string[0];
            }
        }
        else
        {
            strValues = txtText.Trim().Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
        }

        foreach (string strValue in strValues)
        {
            SupportVideos objSupportVideos = new SupportVideos();
            objSupportVideos.VideoTitleAR = objSupportVideos.VideoTitleEN = objSupportVideos.VideoDescriptionAR = objSupportVideos.VideoDescriptionEN = "%" + strValue + "%";
            List<SupportVideos> lstSupportVideos = objSupportVideosDB.SearchOrLike(objSupportVideos);
            //lstTicketType = new List<TicketType>(from objFol in lstTicketType where objFol.StatusID != 2 select objFol);
            //no status
            foreach (SupportVideos objFol in lstSupportVideos)
            {
                if ((from objIn in lstRet where objIn.ID == objFol.ID select objIn).ToList().Count == 0)
                {
                    lstRet.Add(objFol);
                }
            }

        }


        return lstRet;



    }





    protected void grdUsers_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        string strDeletedFile = "";
        
        

        //security check

        if (!mobjUser.lstAllRulesIDs.Contains((long)RulesEnum.Edit_Support_videos))
        {
            lblError.Text = "Security error , you can view only";
            lblResult.Text = "";

            return;
        }


        long SupportVideosID = long.Parse(grdUsers.DataKeys[e.RowIndex]["ID"].ToString());



        SupportVideosDB objSupportVideosDB = new SupportVideosDB(ConnectionStrings.LMS);
        List<SupportVideos> lstSupportVideos = objSupportVideosDB.getSupportVideosByID(SupportVideosID);




        if (lstSupportVideos.Count == 0)
        {
            lblError.Text = "No Support Videos to delete";
            lblResult.Text = "";
            return;
        }



        strDeletedFile = lstSupportVideos[0].VideoFile;


        objSupportVideosDB.Delete(lstSupportVideos[0]);
        try
        {
            File.Delete(Server.MapPath("./SupportVideos/" + strDeletedFile));
        }
        catch
        {
        }


        lblResult.Text = "Deleted ok.";



        bindGrid(txtSearch.Text);



    }




    protected void btnNew_Click(object sender, EventArgs e)
    {
        clearAllControls();
    }



    protected void grdUsers_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grdUsers.DataSource = lstSupportVideosGrid;
        grdUsers.PageIndex = e.NewPageIndex;

        grdUsers.DataBind(); 
    }


    /// <summary>
    /// this function will check mSupportVideosID to detect update or insert
    /// </summary>
    protected void checkID()
    {
        if (mSupportVideosID != -1)
        {
            try
            {

                SupportVideosDB objSupportVideosDB = new SupportVideosDB(ConnectionStrings.LMS);
                List<SupportVideos> lstSupportVideos = objSupportVideosDB.getSupportVideosByID(mSupportVideosID);
                if (lstSupportVideos.Count > 0)
                {


                    mObjSupportVideos = lstSupportVideos[0];
                    if (!mobjUser.lstAllRulesIDs.Contains((long)RulesEnum.Edit_Support_videos))
                        btnDelete.Visible = true;
                    else
                        btnDelete.Visible = false;

                }
                else
                {
                    mSupportVideosID = ((long)-1);
                    btnDelete.Visible = false;
                    
                }


            }
            catch
            {
                mSupportVideosID = ((long)-1);
                btnDelete.Visible = false;
            }


            
        }
        else
        {
            btnDelete.Visible = false;

        }
    }



    /// <summary>
    /// this will bind the SupportVideos to update or delete
    /// </summary>
    protected void BindAllControls()
    {
        txtVideoTitleAR.Text = mObjSupportVideos.VideoTitleAR;
        txtVideoTitleEN.Text = mObjSupportVideos.VideoTitleEN;

        txtVideoDescriptionAR.Text = mObjSupportVideos.VideoDescriptionAR;
        txtVideoDescriptionEN.Text = mObjSupportVideos.VideoDescriptionEN;

        hlVideoFile.Text = mObjSupportVideos.VideoFile;

        hlVideoFile.NavigateUrl = "./SupportVideos/" + mObjSupportVideos.VideoFile;



       
    }



    /// <summary>
    /// this function will read all controls values
    /// </summary>
    protected void ReadAllControls()
    {


        mObjSupportVideos.VideoTitleAR = txtVideoTitleAR.Text;
        mObjSupportVideos.VideoTitleEN = txtVideoTitleEN.Text;

        mObjSupportVideos.VideoDescriptionAR = txtVideoDescriptionAR.Text;
        mObjSupportVideos.VideoDescriptionEN = txtVideoDescriptionEN.Text;

        if (flVideoFile.HasFile)
        {
            
            FileInfo fi = new FileInfo(flVideoFile.FileName);

            string strNewFileName = System.Guid.NewGuid().ToString() + fi.Extension;

            flVideoFile.SaveAs(Server.MapPath("./SupportVideos/" + strNewFileName));

            strChangedFiles = mObjSupportVideos.VideoFile;

            mObjSupportVideos.VideoFile = strNewFileName;
        }
        





       
               



    }



    /// <summary>
    /// this function for clearing controls
    /// </summary>
    protected void clearAllControls()
    {

        txtVideoTitleAR.Text = "";
        txtVideoTitleEN.Text = "";

        txtVideoDescriptionAR.Text = "";
        txtVideoDescriptionEN.Text = "";

        hlVideoFile.Text = "";

        hlVideoFile.NavigateUrl = "#";

        mObjSupportVideos = new SupportVideos();
        mSupportVideosID = -1;

    }



    /// <summary>
    /// this function for loading the editing behavior
    /// </summary>
    protected void editLoad()
    {



            
       

            checkID();


            BindAllControls();




        
    }



    /// <summary>
    /// this function will Save the SupportVideos
    /// </summary>
    protected void Save()
    {


        if (checkForRepeats())
        {
            SupportVideosDB objSupportVideosDB = new SupportVideosDB(ConnectionStrings.LMS);
            if (mObjSupportVideos.ID == -1)
            {
                objSupportVideosDB.Insert(mObjSupportVideos);
                clearAllControls();
                bindGrid(txtSearch.Text);
                lblResult.Text = "Data saved ok.";
            }
            else
            {
                objSupportVideosDB.Update(mObjSupportVideos);
                BindAllControls();
                bindGrid(txtSearch.Text);
                lblResult.Text = "Data saved ok.";

            }

            try { File.Delete(Server.MapPath("./SupportVideos/" + strChangedFiles)); }
            catch { }

        }


    }


    /// <summary>
    /// this function will check if a SupportVideos  exists with the same Title or not
    /// </summary>
    /// <returns>true if ok , false for error (SupportVideos exists before)</returns>
    protected bool checkForRepeats()
    {
        SupportVideosDB objSupportVideosDB = new SupportVideosDB(ConnectionStrings.LMS);



        List<SupportVideos> lstOldSupportVideos = objSupportVideosDB.getSupportVideosByVideoTitleAR (mObjSupportVideos.VideoTitleAR);

        List<SupportVideos> lstExist = new List<SupportVideos>(from objOrg in lstOldSupportVideos where (objOrg.VideoTitleAR == mObjSupportVideos.VideoTitleAR && objOrg.ID != mObjSupportVideos.ID) select objOrg);

        if (lstExist.Count > 0)
        {

            errorExist();
            return false;
        }


        lstOldSupportVideos = objSupportVideosDB.getSupportVideosByVideoTitleEN(mObjSupportVideos.VideoTitleEN);

        lstExist = new List<SupportVideos>(from objOrg in lstOldSupportVideos where (objOrg.VideoTitleEN == mObjSupportVideos.VideoTitleEN && objOrg.ID != mObjSupportVideos.ID) select objOrg);

        if (lstExist.Count > 0)
        {

            errorExist();
            return false;
        }





        return true;

    }




    /// <summary>
    /// this function will show a message with the error for existense
    /// </summary>
    private void errorExist()
    {

        lblError.Text = "Error , a Support video with the same title  is already found , choose a new title";

    }



    protected void btnSave_Click(object sender, EventArgs e)
    {

        


        if (Page.IsValid)
        {



            ReadAllControls();






            Save();


        }
    }




    protected void btnDelete_Click(object sender, EventArgs e)
    {

        string strDeletedFile = "";



        //security check

        if (!mobjUser.lstAllRulesIDs.Contains((long)RulesEnum.Edit_Support_videos))
        {
            lblError.Text = "Security error , you can view only";
            lblResult.Text = "";

            return;
        }


        long SupportVideosID = mSupportVideosID;



        SupportVideosDB objSupportVideosDB = new SupportVideosDB(ConnectionStrings.LMS);
        List<SupportVideos> lstSupportVideos = objSupportVideosDB.getSupportVideosByID(SupportVideosID);




        if (lstSupportVideos.Count == 0)
        {
            lblError.Text = "No Support Videos to delete";
            lblResult.Text = "";
            return;
        }



        strDeletedFile = lstSupportVideos[0].VideoFile;


        objSupportVideosDB.Delete(lstSupportVideos[0]);
        try
        {
            File.Delete(Server.MapPath("./SupportVideos/" + strDeletedFile));
        }
        catch
        {
        }


        lblResult.Text = "Deleted ok.";



        bindGrid(txtSearch.Text);



        

        clearAllControls();






    }




    protected void grdUsers_RowEditing(object sender, GridViewEditEventArgs e)
    {




        long SupportVideosID = long.Parse(grdUsers.DataKeys[e.NewEditIndex]["ID"].ToString());

        mSupportVideosID = SupportVideosID;

        editLoad();

        e.Cancel = true;

        

    }



    


    protected void cvVideoFile_ServerValidate(object source, ServerValidateEventArgs args)
    {
        if (flVideoFile.HasFile)
        {
            args.IsValid = true;
            return;
        }
        else if (hlVideoFile.Text != "")
        {
            args.IsValid = true;
            return;

        }
        else
        {
            args.IsValid = false;
            return;
        }
    }
    protected void grdUsers_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            SupportVideosDB objSupportVideosDB = new SupportVideosDB(ConnectionStrings.LMS);


            long SupportVideosID = 0;
            long.TryParse(grdUsers.DataKeys[e.Row.RowIndex]["ID"].ToString(), out SupportVideosID);

            List<SupportVideos> lstSupportVideos = objSupportVideosDB.getSupportVideosByID(SupportVideosID);

            if (lstSupportVideos.Count == 0)
                return;

            try
            {
                FileInfo fi = new FileInfo(Server.MapPath("./SupportVideos/" + lstSupportVideos[0].VideoFile));

                Label lblSize = new Label();

                Panel pnlFileSize = (Panel)e.Row.FindControl("pnlFileSize");

                lblSize.Text = (((float)fi.Length) / (1024 * 1024)).ToString("f3");
                pnlFileSize.Controls.Add(lblSize);
            }
            catch
            {
            }

        }
    }
}
